const MongoClient = require('mongodb').MongoClient

// conection url
const url = 'mongodb://localhost:27017/myproject'

MongoClient.connect(url, function (err, db) {
  if (err) {
    return console.dir(err)
  }
  console.log('Connected to mongodb')

  // InsertDocument(db, function () {
  //   db.close()
  // })

  // InsertDocuments(db, function () {
  //   db.close()
  // })

  // FindDocuments(db, function () {
  //   db.close()
  // })

  // QueryDocuments(db, function () {
  //   db.close()
  // })

  // UpdateDocuments(db, function () {
  //   db.close()
  // })

  // RemoveDocument(db, function () {
  //   db.close()
  // })

})

// insert single doc
const InsertDocument = function (db, callback) {
  // get collection
  const collection = db.collection('users')
  // insert docs
  collection.insert({
    name: 'Brad Doe',
    email: 'brad@doe.com'
  }, function (err, result) {
    if (err) {
      return console.dir(err)
    }
    console.log('Inserted Document')
    console.log(result)
    callback(result)

  })
}

// insert multiple docs
const InsertDocuments = function (db, callback) {
  // Get Colletions
  const collection = db.collection('users')
  collection.insertMany([
    {
      name: 'John Doe',
      email: 'john@test.com'
    },
    {
      name: 'Silvia Doe',
      email: 'silvia@souza.com'
    },
    {
      name: 'Renata Silva',
      email: 'renata@test.com'
    }
  ], function (err, result) {
    if (err) {
      return console.dir(err)
    }
    console.log('Inserted ' + result.ops.length + ' documents')
    console.log(result)
    callback(result)

  })

}


const FindDocuments = function (db, callback) {
  // Get Colletions
  const collection = db.collection('users')

  collection.find({}).toArray(function (err, docs) {
    if (err) {
      return console.dir(err)
    }
    console.log('Found the following records')
    console.log(docs)
    callback(docs)
  })

}


const QueryDocuments = function (db, callback) {
  // Get Colletions
  const collection = db.collection('users')
  collection.find({ 'name': 'John Doe' }).toArray(function (err, docs) {
    if (err) {
      return console.dir(err)
    }
    console.log('Found the following records')
    console.log(docs)
    callback(docs)
  })

}

// Update Documents
const UpdateDocuments = function (db, callback) {
  // Get Colletions
  const collection = db.collection('users')
  collection.updateOne({ name: 'John Doe' }, { $set: { email: 'john@algumacoisa.ml' } }, function (err, result) {
    if (err) {
      return console.dir(err)
    }
    console.log('Updated Document')
    callback(result)
  })

}

const RemoveDocument = function (db, callback) {
  // Get Colletions
  const collection = db.collection('users')

  collection.deleteOne({ name: 'John Doe' }, function (err, result) {
    if (err) {
      return console.dir(err)
    }
    console.log('Remove Document')
    console.log(result)
    callback(result)
  })

}


